<!--  -->
<template>
    <div>

        <van-form @submit="onSubmit" @failed="failedMethod">

            <!-- 头 -->
            <div class="font15 mt10">
                <div class="pl10">
                    <span class="titletext ">{{ params.isDrawup == '1' ? '发起项目交接' : nFromdata.title }}</span>
                </div>

                <div v-if="params.isDrawup != '1'" class="graytext mt10 mb5 font13 pl10">
                    <span>工单编号：</span>
                    <span class="titletext">{{ nFromdata.pmInsId }}</span>
                </div>

                <div v-if="params.isDrawup == '1'" class="redtext mt10 mb5 font13 pl10">
                    <span>提示：该表单带*字段都为必填项</span>
                </div>

                <div class="bcolor-e" style="height: 8px;"></div>
            </div>


            <van-tabs v-model="active" color="#1989fa" sticky animated line-width="33%" offset-top="50">

                <van-tab title="基础信息">
                    <table-one ref="toMsgs" :params="params" :fromdata='fromdata' :mFromdata="mFromdata"
                        :decisionMaking="decisionMaking" :approveList='approveList' :historydata='historydata'
                        :isSJ='isSJ' @freshSysFiles='freshSysFiles($event)' @freshAnalysisData='freshAnalysisData($event)' @freshIdKey='freshIdKey($event)' @freshCountyCode='freshCountyCode($event)' :aiDataResult="aiDataResult"/>
                </van-tab>

                <van-tab title="其他信息">
                    <table-two :params="params" :mFromdata='mFromdata' />
                </van-tab>
            </van-tabs>


            <!-- 跳转意见 -->
            <div v-if="showOpinionMoudle" class="left_botton">
                <button block type="button" @click="toMsgValue()" style="color:#60a9ec; display: inline-block;width:100%;border: 0px solid #60a9ec;border-radius: 15px 0px 0px 15px;
            padding:10px 10px 10px 15px;font-size:13px">意见</button>
            </div>

            
            <!-- 流转下一步 -->
            <div v-if="showNextButton" class="footer">
                <van-button block type="info" native-type="submit" :disabled="!canToNext"
                    style="display: inline-block; width: 100%; border: 0px solid #60a9ec">{{ buttonTitle }}</van-button>
            </div>
        </van-form>


    </div>
</template>


<script>



import { mapGetters } from "vuex";
import { Notify, Dialog, showConfirmDialog , Toast } from "vant";
import util from "@/assets/js/public";
import {
  getSZTDZJFormDetail,
  getProjectDelNewInformation,
  getWfOptMags,
  getWfLinkTracks,
  getSrqrRequest,
  fileParsingRequestAnalysisFlowQuery,
  fileParsingCurrencyHttp,
  saveFileParsingRequestLog,
  getPublicCountyCode,
} from "@/api/dictapi";

import TableOne from './tableOne.vue';
import TableTwo from './tableTwo.vue';
import jTool from "../../assets/js/jHelper";
import aiUtils from "@/assets/js/aiUtils";
import num_regx from "chai/chai";


export default {
    data() {
        return {

            active: 0,

            fromdata: {},
            nFromdata: {},
            mFromdata: {
                stakeholder: [],
                contractDeliveryInfo: [],
                partnerInfo: [],
                newContractFile: [],
                projectDecisionDocument: [],
            },

            decisionMaking: {
                meetingTheme: '',
                meetingThemeCompany: ''
            },

            params: this.$route.query,
            todotype: false,
            approveList: [],
            fileList: [],
            fileindex: 0,
            showHistory: false,
            historydata: {},
            toRead: false,
            zhenbieData: {},
            chLocationName: "",
            participantName: "",

            buttonTitle: '流转下一步',
            canToNext: true,
            aiDataResult :{},
            isSJ: false,  /// 决策层级是不是省级
          sysFiles:[],
          analysisData:[],
          idKey:''
        };
    },

    computed: {

        ...mapGetters(["user"]),
        ...mapGetters(["userinfo"]),


        formEditable() {
            return this.params.location === 'dict.start' || this.params.isDrawup == '1';
        },

        /// 意见
        showOpinionMoudle() {
            return this.params.isDrawup != '1';
        },



        showNextButton() {
            return this.todotype || this.toRead || this.params.isDrawup == '1';
        }
    },
    activated() {
      if (localStorage.getItem('xmdjType') != '{}' && localStorage.getItem('xmdjType')) {
        this.fromdata.onProjectGradeFinal = JSON.parse(localStorage.getItem('xmdjType'))
        localStorage.setItem('xmdjType', '{}')
      }
    },
    beforeRouteEnter(to, from, next) {

        next(vm => {

            // console.log('AA', to, 'AAAA', from);
            // 起草 - 从二级”列表“进来（界面因为保活问题，第二次从”列表“进来的时候 created方法不会重新调用，所以需要确保”列表“进来（或唤醒）时，要刷新起草数据）
            // 通过 `vm` 访问组件实例
            if (to.query.isDrawup == '1' && from.name === 'drawup_transition_tab') {

                vm.params = to.query;
                vm.requestDrawupInfo(to.query.projectInformationId);
            }
        });
    },

    //生命周期--创建完成
    created() {

        /// 办理 - 从待办进来（界面每次都会重新创建，所以不需要考虑缓存的问题）
        if (this.$route.query.isDrawup != '1') {

            if (this.params.pmInsType == null && this.params.processType != null) {
                this.params.pmInsType = this.params.processType
            }

            if (this.params.todoType == "1") {
                this.todotype = true;
            }
            else if (this.params.todoType == "2") {
                this.showHistory = true;
            }
            else if (this.params.todoType == "3") {
                this.toRead = true;
            }

            this.getdetail();
        }


    },

    //生命周期--挂载完成
    components: {

        TableOne,
        TableTwo
    },

    //生命周期--挂载完成
    mounted() { },

    //方法调用
    methods: {
        freshSysFiles(value){
          this.sysFiles=value
        },
        freshAnalysisData(value){
          this.analysisData=value
        },
        freshIdKey(value){
          this.idKey=value
        },
        freshCountyCode(value){
          console.log('选择的县区code是'+value)
          this.fromdata.publicCountyCode=value
        },
        failedMethod(data) {

            const errorArr = data.errors;
            const errorObj = errorArr[0];
            const errorMessage = errorObj.message;
            Toast({ type: 'text', message: errorMessage, duration: 1000 });
        },
        
        toMsgValue() {
            this.$refs.toMsgs.tomsg()
        },

        // TODO: 网络请求
        getdetail() {
            Toast.loading({ message: "加载中", forbidClick: false });
            getSZTDZJFormDetail(
                Object.assign(this.params, { userName: this.user.userName })
            ).then((result) => {
                this.fromdetal = {};
                Toast.clear();

                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {
                    this.nFromdata = result.data.data;
                }

                this.getDecisionMakingByPmInsId(result.data.data.projectInformationId);
            })

            getWfOptMags(Object.assign(this.params), {
                userName: this.user.userName,
            }).then((result) => {
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }
                this.approveList = result.data.data.reverse();
            })

            if (this.showHistory) {

                getWfLinkTracks(Object.assign(this.params), {
                    userName: this.user.userName,
                }).then((result) => {
                    Toast.clear();
                    if (!result.data) {
                        Notify(result.message);
                        return;
                    }
                    if (result.data.data) {
                        //数据过滤，并生成新的数组
                        this.historydata = result.data.data.filter(
                            (item) => item.CURRENTSTATE == 10
                        )[0];
                        if (this.historydata) {
                            if (this.historydata.MANAGER) {
                                this.showHistory = true;
                            } else {
                                this.showHistory = false;
                            }
                        } else {
                            this.showHistory = false;
                        }
                    } else {
                        this.showHistory = false;
                    }
                })
            }
        },

        getDecisionMakingByPmInsId(projectInformationId) {

            Toast.loading({ message: "加载中", forbidClick: false });
            getProjectDelNewInformation(projectInformationId).then((result) => {

                this.fromdetal = {};
                Toast.clear();
                if (!result.data) {
                    Notify(result.message);
                    return;
                }

                if (result.data.data) {

                    this.mFromdata = result.data.data;
                    this.decisionMaking = result.data.data.decisionMaking;
                    this.fromdata = result.data.data.projectInformationForm;
                    this.fromdata.competitiveMode = result.data.data.projectApproval.competitiveMode;

                    if (jTool.stringIsEmpty(this.decisionMaking.decisionLevel)) {
                        this.decisionMaking.decisionLevel = '';
                    }

                    if (this.decisionMaking.decisionLevel.search('省') >= 0) {
                        this.isSJ = true;
                    }
                    if(this.fromdata.newContractFile){
                      Toast.loading({ message: "加载中", forbidClick: false, });
                      fileParsingRequestAnalysisFlowQuery(Object.assign(this.params, { userName: this.user.userName, fileId: this.fromdata.newContractFile[0].id })).then((result) => {
                        Toast.clear();
                        if (!result.data) {
                          Notify(result.message);
                          return;
                        }
                        if (result.data.data) {
                          this.aiDataResult = result.data.data;
                        }
                      });
                    }
                    this.getPublicCountyCode();
                }
            });
        },
        getPublicCountyCode() {
          getPublicCountyCode({userName:this.user.userName,city:this.fromdata.city})
              .then((result)=>{
                Toast.clear();
                if(!result.data){
                  Notify(result.message);
                  return;
                }
                if(result.data.data){
                  let cityList=result.data.data
                  for (let i in cityList){
                    if (cityList[i].value==this.fromdata.publicCountyCode){
                      this.fromdata={...this.fromdata,...{publicCountyCodeValue:cityList[i].name}}
                      break
                    }
                  }
                }
              })
        },
        requestDrawupInfo(projectInformationId) {
            this.getDecisionMakingByPmInsId(projectInformationId);
        },

        checkCanSubmit() {

            var canSubmit = true;
            if (this.isSJ) {

                if (!this.decisionMaking.meetingNumberCompany || !this.decisionMaking.meetingThemeCompany) {
                    canSubmit = false;
                }
            }
            else {
                if (!this.decisionMaking.meetingNumber || !this.decisionMaking.meetingTheme) {
                    canSubmit = false;
                }
            }

            if (!canSubmit) {

                Dialog.alert({
                    title: "提示",
                    message: "如需选择关联会议纪要，请至PC端办理。",
                }).then(() => {

                });

                return false;
            }

            return true;
        },

        onSubmit() {
          if (this.formEditable&&this.analysisData&&this.analysisData.length>0&&this.sysFiles&&this.sysFiles.length>0){
            Toast.loading({ message: '数据保存中...', forbidClick: false });
            saveFileParsingRequestLog(Object.assign(this.params, { userName: this.user.userName,id:this.idKey ,fileId: this.sysFiles[0].id, detailData:this.analysisData })).then((result) => {
              Toast.clear();
              if (!result.data) {
                Notify(result.message);
                return;
              }
              if (result.data.errcode===0) {
                this.onNextsubmit();
              }
            })
          }
          else {
            this.onNextsubmit();
          }
        },
        onNextsubmit(){
          if (!this.checkCanSubmit()) {
            return;
          }
          //这里新增项目交接内嵌人工稽核业务逻辑，然后再走原来逻辑
          this.checkJiheSwitch(this.fromdata.projectID,function (){
            this.controlRule(this.params, this.fromdata.projectID, function () {
              this.onNext();
            }.bind(this));
          })
        },
        checkJiheSwitch(projectNumber,nextFun){
          Toast.loading({message:'加载中', forbidClick:false});
          getSrqrRequest("queryDictValue$api$queryByType",{
            kv: {
              "source": 'MOBILE',
              "dictType": 'systemCheckSystemSwitch',
              "currentUserCode": util.encrypt(this.user.userName),
            }
          }) .then((result)=>{
            Toast.clear();
            if(result.responseid==1){//请求成功
              if(result.data.data && result.data.data[0].value == "ON"){
                this.queryOrderJihe(projectNumber,nextFun);
              }else{
                nextFun();
              }
            }else{
              Notify("查询稽核开关状态失败："+result.message);
            }
          }).catch(() => {
            Toast.clear();
            Notify("查询稽核开关状态失败");
          });
        },
      queryOrderJihe(projectNumber,nextFun){
        Toast.loading({message:'加载中', forbidClick:false});
        getSrqrRequest("checkSystemController$api$queryProjectHandoverCheckSystemOrder",{
          kv: {
            "source": 'MOBILE',
            "projectNumber": projectNumber,
            "currentUserCode": util.encrypt(this.user.userName),
          }
        }) .then((result)=>{
          Toast.clear();
          if(result.responseid==1) {//请求成功
            let resData = result.data.data;
            if (!resData && "稽核工单未发起" === result.data.message) {
              this.sendOrderJihe(projectNumber);
            } else if (resData && resData.dealResult == "通过") {
              nextFun()
            } else if (resData && resData.dealResult == "不通过") {
              showConfirmDialog({
                title: '温馨提示',
                message:
                    "稽核系统未通过,稽核状态为:【"+resData.dealResult+"】,处理人员为:【"+resData.dealName+"】,处理人员电话为:【"+resData.dealPhone+"】,处理意见为:【"+resData.opRemarks+"】，确认是否重新发起稽核？",
              }).then(() => {
                    this.sendOrderJihe(projectNumber);
                  });
            }
          }else{
            Notify("查询工单稽核状态失败："+result.message);
          }
        }).catch(() => {
          Toast.clear();
          Notify("查询工单稽核状态失败");
        });
      },
      sendOrderJihe(projectNumber){
        Toast.loading({message:'加载中', forbidClick:false});
        getSrqrRequest("checkSystemController$api$sendProjectHandoverCheckSystem",{
          kv: {
            "source": 'MOBILE',
            "projectNumber": projectNumber,
            "type": "add",
            "currentUserCode": util.encrypt(this.user.userName),
          }
        }) .then((result)=>{
          Toast.clear();
          if(result.responseid==1){//请求成功
            Notify("已发送稽核请求");
          }else{
            Notify("发送稽核请求失败:"+result.data.message);
          }

        }).catch(() => {
          Toast.clear();
          Notify("发送稽核请求失败");
        });
      },
        // 流转下一步
        onNext() {
            var newFromdata = JSON.parse(JSON.stringify(this.fromdata));
            var htmlParamMap = Object.assign(newFromdata, this.mFromdata);
            htmlParamMap.stakeholderInfo = this.mFromdata.stakeholder;

            var formSendData = { "htmlParamMap": {} };
            formSendData.htmlParamMap = htmlParamMap;
            formSendData.id = this.nFromdata.id;
            formSendData.pmInsId = this.nFromdata.pmInsId;
            formSendData.processType = this.params.pmInsType
            formSendData.workItemId = this.params.workItemId;

            let currentUserCode = util.encrypt(this.user.userName);

            var params1 = {
                kv: {
                    currentUserCode: currentUserCode,
                    source: 'MOBILE',
                    location: this.params.location,
                    processInstId: this.params.processInstId,
                    processDefName: this.params.processDefName,
                    processType: this.params.pmInsType,
                },
            };

            var params2 = {
                kv: {
                    "currentUserCode": currentUserCode,
                    "source": 'MOBILE',
                    "location": this.params.location,
                    "processInstId": this.params.processInstId,
                    'processType': this.params.pmInsType,
                    'receiptCode': this.params.processInstId
                },
            };
            var params3 = {
                kv: {
                    "source": 'MOBILE',
                    "currentUserCode": currentUserCode,
                    "workItemId": this.params.todoType == 3 ? "" : this.params.workItemId,
                    "processInstId": this.params.processInstId,
                    "location": this.params.location,
                    "notificationId": this.params.todoType == 3 ? this.params.wfnid : ""
                },
            };

            localStorage.setItem('submitPageParam', JSON.stringify({
                getDecisionsUrl: 'decisionAndUser$api$getDecisions',
                getUserUrl: 'decisionAndUser$api$getOrgAndUser',
                tosubmintUrl: 'applicationFormProject$api$startSubmitProcess',

                getDecisionsParams: params1,
                getUserParams: params2,
                tosubmintParams: params3,
                formData: formSendData,
                fromMoa: this.params.fromMoa,
                type: this.params.todoType == 3 ? "toRead" : "toDo"
            }));

            this.$router.push({
                name: "srqrsubmit"
            });
        },



        

    },
};
</script>

<style scoped>
/* @import url();*/
</style>